package com.yun.controller;

import com.aliyun.oss.OSSClient;
import com.yun.pojo.UpdPwd;
import com.yun.pojo.User;
import com.yun.service.UserService;
import com.yun.unit.Code;
import com.yun.unit.Oss;
import com.yun.unit.R;
import net.sf.jsqlparser.schema.MultiPartName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Oss oss;
    //注册
    @RequestMapping("/ins")
    public R register(@RequestBody User user){
        return userService.register(user);
    }
    //登录
    @RequestMapping("/login")
    public R login(@RequestBody User user){
        return userService.login(user);
    }
    //忘记密码
    @RequestMapping("/wang")
    public R forget(@RequestBody User user){
        return userService.forget(user);
    }
    //修改密码
    @PostMapping("/upd")
    public R updatePassword(@RequestBody UpdPwd user){
        System.out.println(user);
        return userService.updatePassword(user);
    }
    //修改用户信息
    @PostMapping("/updUser")
    public R updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }

    //将用户上传的头像存放打阿里云上
    @PostMapping("/updImg")
    public R updateImg(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        String newname = UUID.randomUUID().toString().substring(24) + "-" + originalFilename;
        OSSClient xx = new OSSClient(oss.getUrl(), oss.getId(), oss.getSecret());
        xx.putObject(oss.getTong(), newname, file.getInputStream());
        String url1 = oss.getUrl();
        String[] split = url1.split("//");
        String url = split[0] + "//" + oss.getTong() + "." + split[1] + "/" + newname;
        return new R(Code.get_ok,"上传成功",url);
    }
    //将头像的路径保存到数据库中
    @PostMapping("/updImgUrl")
    public R updateImgUrl(@RequestBody User user){
        System.out.println(user);
        return userService.updateImgUrl(user);
    }

    //根据用户id查询用户信息
    @GetMapping("/selById/{id}")
    public R selById(@PathVariable Integer id){
        return userService.selById(id);
    }
}
